package edu.ntu.im.p2ptrade.msg.handle;

import java.util.ArrayList;
import java.util.List;

import net.jxta.endpoint.Message;
import net.jxta.endpoint.MessageElement;
import net.jxta.endpoint.Message.ElementIterator;
import edu.ntu.im.p2ptrade.P2PTrade;
import edu.ntu.im.p2ptrade.entity.Item;
import edu.ntu.im.p2ptrade.entity.PeerItemRepository;
import edu.ntu.im.p2ptrade.msg.MyItems;
import edu.ntu.im.p2ptrade.msg.PMessage;

public class MyItemHandle implements PMessageHandle {

	public void handle(Message msg) {
		//TODO: finish it !!
		String peer = msg.getMessageElement(P2PTrade.getInstance().getAppName(), PMessage.PEER).toString();
		
		List<Item> items = msg2Items(msg, peer);
		
		PeerItemRepository.getInstance().setItems(peer, items);

	}

	static List<Item> msg2Items(Message msg, String peer) {
		ElementIterator itr = msg.getMessageElements(P2PTrade.getInstance().getAppName(), MyItems.IID);
		List<Item> items= new ArrayList<Item>();
		while(itr.hasNext()){
			Item item = new Item(peer, null);
			MessageElement mg = itr.next();
			item.setId(Integer.parseInt(mg.toString()));
//			item.setOwnerId();
			items.add(item);
		}
		ElementIterator itr2 = msg.getMessageElements(P2PTrade.getInstance().getAppName(), MyItems.INAME);
		Integer index = 0;
		while (itr2.hasNext()){
			MessageElement mg = itr2.next();
			items.get(index++).setName(mg.toString());
			System.out.println("name:"+mg.toString());
		}
		ElementIterator itr3 = msg.getMessageElements(P2PTrade.getInstance().getAppName(), MyItems.IMEMO);
		Integer index2 = 0;
		while (itr3.hasNext()){
			MessageElement mg = itr3.next();
			items.get(index2++).setMemo(mg.toString());
			System.out.println("memo:"+mg.toString());
		}
		ElementIterator itr4 = msg.getMessageElements(P2PTrade.getInstance().getAppName(), MyItems.IPICURL);
		Integer index3 = 0;
		while (itr4.hasNext()){
			MessageElement mg = itr4.next();
			items.get(index3++).setPhotoUrl(mg.toString());
			System.out.println("photoURL:"+mg.toString());
		}
		
		return items;
	}

}
